package cn.hunqing.web.service.impl;

import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import cn.hunqing.web.dto.WeChatShareDto;
import cn.hunqing.web.service.WeChatService;
import cn.hunqing.web.util.WeChatUtils;

@Service
public class WeChatServiceImpl implements WeChatService{

	private static final Logger LOG = LoggerFactory.getLogger(WeChatServiceImpl.class.getName());
	private static final ConcurrentHashMap<String, String> concurrentHashMap=new ConcurrentHashMap<String, String>();
	
	private static final String WECHAT_TOKEN = "WeChatToken";
	
	@Override
	public WeChatShareDto getShareConfig(String url){
		WeChatShareDto newWeChatShareDto = new WeChatShareDto();
		newWeChatShareDto.setAppId(WeChatUtils.APP_ID);

		String timeStamp = Long.toString(new Date().getTime()).substring(0, 10);
		String nonceStr = RandomStringUtils.randomAlphanumeric(10);
		newWeChatShareDto.setTimestamp(timeStamp);
		newWeChatShareDto.setNonceStr(nonceStr);
		
		String token = concurrentHashMap.get(WECHAT_TOKEN);
		if(StringUtils.isEmpty(token)){
			token = WeChatUtils.getToken();
			concurrentHashMap.put(WECHAT_TOKEN, token);
		}
		LOG.info("Get the token from WeChat:{}", token);
		String jsTicket = WeChatUtils.getjsTicket(token);
		
		if(StringUtils.isEmpty(jsTicket)){
			token = WeChatUtils.getToken();
			concurrentHashMap.put(WECHAT_TOKEN, token);
			jsTicket = WeChatUtils.getjsTicket(token);
		}
		LOG.info("Get the jsTicket from WeChat:{}", jsTicket);
		String signature = WeChatUtils.getSignature(jsTicket, timeStamp, nonceStr, url);
		LOG.info("Get the signature from WeChat:{}", signature);
		newWeChatShareDto.setSignature(signature);
		newWeChatShareDto.setLink(url);
		return newWeChatShareDto;
	}
}
